<?php
/**
 * 客户操作日志控制器
 */

namespace app\controller\customer;

use app\BaseController;
use app\model\customer\CustomerLog as CustomerLogModel; // 修复：使用正确的模型类名
use app\model\admin\User as UserModel; // 引入User模型

class Log extends BaseController
{
    /**
     * 查看操作日志列表
     */
    public function list()
    {
        $customer_id = input('customer_id');
        $page = input('page', 1);
        $limit = input('limit', 10);
        
        $where = [];
        if ($customer_id) {
            $where[] = ['customer_id', '=', $customer_id];
        }
        
        // 关联查询User模型获取管理员名称
        $list = CustomerLogModel::where($where)
            ->with(['admin' => function($query) {
                $query->field('id,username,nickname'); // 只查询需要的字段
            }])
            ->order('create_time', 'desc')
            ->paginate($limit, false, ['page' => $page]);
            
        // 处理数据，添加admin_name字段
        $items = $list->items();
        foreach ($items as &$item) {
            // 确保时间字段是整数
            $item['create_time'] = isset($item['create_time']) ? (int)$item['create_time'] : 0;
            
            // 从关联的admin对象中获取名称，优先使用nickname，其次username
            if (isset($item['admin'])) {
                $item['admin_name'] = $item['admin']['nickname'] ?: $item['admin']['username'];
                unset($item['admin']); // 移除admin对象，只保留需要的字段
            } else {
                $item['admin_name'] = '';
            }
        }
            
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $items,
            'count' => $list->total()
        ]);
    }
}
